
import { LoginQuery } from '../services/login'
import { Toast } from 'antd-mobile'
import { Actions } from 'react-native-router-flux'
import callApi from '../../src/utils/callApi'
import {AsyncStorage} from "react-native";
function showToast(){
  Toast.fail('用户名或密码错误！', 1)
}

//存登录信息用的key
const thisLoginInfoes = 'LOGININFOES';
//存登录信息
function saveFavoriteItem(userInfo){
    AsyncStorage.setItem(thisLoginInfoes, JSON.stringify(userInfo), function(err){
        if (err) {
            return;
        }
    });
}
//获取存下的登录信息
function getUserInfo() {
    return new Promise((resolve, reject )=> {
        AsyncStorage.getItem(thisLoginInfoes, function(err, result) {
            // console.log(err, result)
            if (err) {
                reject(err)
            }
            resolve(JSON.parse(result));
        });
    })
}

//长按短按
var timeCount = null;
let pressTime = 0;//按钮按下后计数

export default {
  namespace: 'login',

  state: {
    loginWait:true,
    userId: '',
    userName: '',//songquanjie 柴浩
    pwd: '',
    role: '',
    confirm: false,
    loading: false,
    headImg:'',
    loginInfoes:{},
    dialogText:'',
    personName:'',
    ViewShow:false,
    ViewShowNum:0
  },

  subscriptions: {
    setup({dispatch, history}){
    },
  },

  effects: {
    *getApi({payload}, {put, select, call}){

        const url = 'http://wh-yth.oss-cn-beijing.aliyuncs.com/appUrl.json'
        const {json, error} = yield callApi(url)

        if(error){

        }else{
          // if(payload === undefined || payload ==='yth'){
          //   for(let i in GLOBAL.INT){
          //     GLOBAL.INT[i] = json.yth_pad + '/api' + GLOBAL.INT[i].split('/api')[1];
          //   }
          // yield put({type:'indexPage/titleCheck',payload:{
          //     thisTitle:'执法监督PAD测试版',
          //     thisType:'YiTiHua'}});
          // }else if(payload ==='tr'){
          //   for(let i in GLOBAL.INT){
          //     GLOBAL.INT[i] = json.tr_pad + '/api' + GLOBAL.INT[i].split('/api')[1];
          //   }
          // yield put({type:'indexPage/titleCheck',payload:{
          //     thisTitle:'铜仁市住建局执法监督PAD',
          //     thisType:'TongRen'}});
          // }else if(payload ==='tj'){
          //   for(let i in GLOBAL.INT){
          //     GLOBAL.INT[i] = json.tj_pad + '/api' + GLOBAL.INT[i].split('/api')[1];
          //   }
          // yield put({type:'indexPage/titleCheck',payload:{
          //     thisTitle:'南港新区建设工程质量检测监管平台',
          //     thisType:'TianJin'}});
          // }else if(payload ==='gy'){
          //   for(let i in GLOBAL.INT){
          //     GLOBAL.INT[i] = json.gy_pad + '/api' + GLOBAL.INT[i].split('/api')[1];
          //   }
          // yield put({type:'indexPage/titleCheck',payload:{
          //     thisTitle:'贵阳市住房和城乡建设局执法行为分析与监督系统',
          //     thisType:'GuiYang'}});
          // }else if(payload ==='ga'){
          //   for(let i in GLOBAL.INT){
          //     GLOBAL.INT[i] = json.ga_pad + '/api' + GLOBAL.INT[i].split('/api')[1];
          //   }
          // yield put({type:'indexPage/titleCheck',payload:{
          //     thisTitle:'贵安新区规划建设管理局执法监督PAD系统',
          //     thisType:'GuiAn'}});
          // }
            yield put({type:'projectDetail/getUrl',payload:json.ga_pad})
            for(let i in GLOBAL.INT){
              GLOBAL.INT[i] = json.ga_pad + '/api' + GLOBAL.INT[i].split('/api')[1];
            }
            yield put({type:'indexPage/titleCheck',payload:{
              thisTitle:'贵安新区规划建设管理局执法监督PAD系统',
              thisType:'GuiAn'}});
          yield put({type:'thisCeshi'});
        }

        let thisGetedInfoes = yield getUserInfo();
        if(thisGetedInfoes == null || thisGetedInfoes === undefined){
            thisGetedInfoes = {
                loginName:'',
                loginPWD:''
            }
        }
        const {loginName,loginPWD} = thisGetedInfoes
        yield put({type:'thisUpdateInfoes',payload:{loginName,loginPWD}});
    },
    *login({payload}, {put, select, call}){

      yield put({type: 'startLoading'})

      const { userName, pwd } = yield select(state => state.login)

      /**
       * 请求参数：userName(用户名)，pwd(密码)
       */
      const { json, error } = yield call(LoginQuery, {loginName: userName, password: pwd})

      let userInfo = {
        loginName:userName, 
        loginPWD:pwd
      }

      if(error || json.code === '0'){
        yield put({type: 'stopLoading'})
        yield put({type:'thisDialog/thisInit'});
        yield put({type:'dialogShow',payload:'用户名或密码错误！'});
      }else{
        yield saveFavoriteItem(userInfo)
        yield put({type: 'stopLoading'})
        yield put({type: 'loginSuccess', payload: json.data})
        Actions.push('IndexPage')//taizhang IndexPage  taiZhangDetail
      }
    },
      //按下按钮开始计数
      *thisPressIn({payload},{put,call,select}){
        //开始计数，100ms计数一次
          timeCount = setInterval(
              ()=>{
                  pressTime += 1;
              },
              100,
          );
      },
      //松开按钮获取按下后的计数值
      *thisPressOut({payload},{put,call,select}){
          timeCount && clearInterval(timeCount);//停止计数
          if(pressTime > 10){
             // 长按状态下的事件
          }else {
              //点击事件，（登录）
              yield put({type:'login'})
          }
          pressTime = 0;
      }
  },

  reducers: {
    change(state, {payload}){
      return { ...state, ...payload}
    },
    startLoading(state){
      return { ...state, loading: true }
    },
    stopLoading(state){
      return { ...state, loading: false }
    },
    loginSuccess(state, {payload}){
      return { ...state,loginInfoes:payload,headImg:payload.photo, userId: payload.id,
          personName:payload.name,role: payload.roleNames, confirm: true,dialogText:'' }
    },
    thisCancled(state){
      return {...state,loginWait:false}
    },
    thisCeshi(state, {payload}){
      return {...state,loginWait:false}
    },
    dialogShow(state,{payload}){
      return {...state,dialogText:payload}
    },
    thisUpdateInfoes(state,{payload}){
        return {...state,userName:payload.loginName,pwd:payload.loginPWD}
    },
    showThisView(state,{payload}){
      return {...state,ViewShow:false,ViewShowNum:0}
    },
    showTheView(state,{payload}){
      let yesShow = false
      if (payload+1 >4){
        yesShow = true
      }else {
        yesShow = false
      }
      return {...state,ViewShow:yesShow,ViewShowNum:payload+1}
    },
  },
}